package test.com.db.server;

import com.db.protocol.Command;
import com.db.protocol.Request;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class FakeClient extends Thread {

    ObjectInputStream in;
    ObjectOutputStream out;

    public FakeClient(ObjectInputStream in, ObjectOutputStream out) {
        this.in = in;
        this.out = out;
    }

    @Override
    public void run() {
        Thread subthread = new Thread() {
            @Override
            public void run() {
                while (!isInterrupted()) {
                    try {
                        System.out.println((String)in.readObject());
                    } catch (ClassNotFoundException | IOException e) {
                        this.interrupt();
                        System.err.println(e);
                    }
                }
            }
        };
        subthread.start();
        try {
            out.writeObject(new Request(Command.chid, new String[]{this.getName()}));
        } catch (IOException e) {
            System.err.println("lol, will be noname");
        }
        while (!isInterrupted()) {
            try {
                for (int i = 0; (HundredsOfFakeClients.SND_PER_HIST < 0 || i < HundredsOfFakeClients.SND_PER_HIST) && !isInterrupted(); ++i) {
                    sleep(HundredsOfFakeClients.SLEEP_TIME);
                    out.writeObject(new Request(Command.snd, new String[]{"my cool story"}));
                }
                out.writeObject(new Request(Command.hist, null));
            } catch (IOException | InterruptedException e) {
                System.err.println("something bad, when sending to server");
            }
        }
        try {
            out.writeObject(new Request(Command.disconnect, null));
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
}
